package models

import (
	"github.com/jinzhu/gorm"
	"time"
	"hytx_media/pkg/logging"
	"fmt"
)

type Article struct {
	ID                int       `gorm:"primary_key" json:"id"`
	Author            int       `json:"author"`
	Title             string    `json:"title"`
	LabelId           string    `json:"label_id"`
	Content           string    `json:"content"`
	Cover             string    `json:"cover"`
	IsAd              bool      `json:"is_ad"`
	ArticleCategoryId int       `json:"article_category_id"`
	Sort              int       `json:"sort"`
	Creator           int       `json:"creator"`
	Pageviews         int       `json:"pageviews"`
	ActualPageviews   int       `json:"actual_pageviews"`
	CommentNum        int       `json:"comment_num"`
	LastCommentAt     time.Time `json:"last_comment_at"`
	Status            int       `json:"status"`
	OperateStatus 	  int		`json:"operate_status"`
	ShareNum          int       `json:"share_num"`
	RecommendNum      int       `json:"recommend_num"`
	CollectNum        int       `json:"collect_num"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
	IsDeleted         bool      `json:"is_deleted"`
	Thumb 			  int 	`json:"thumb"`

}

func (u Article) TableName() string {
	return "articles"
}

// 通过id 判断文章是否存在
func ExistArticleByID(id int) (bool, error) {
	var article Article
	err := DB.Select("id").Where("id =? And is_deleted =0", id).First(&article).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if article.ID > 0 {
		return true, nil
	}
	return false, err
}

// 获取单个文章
func GetArticle(id int) (*Article, error) {
	var article Article
	err := DB.Where("id=? and is_deleted = 0", id).First(&article).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &article, nil
}

// 获取文章列表

func GetArticles(title string,timeWhere string,  pageNum int, pageSize int, maps interface{}) ([]*Article, error) {
	var article []*Article
	err := DB.Where(maps).Where(title).Where(timeWhere).Offset(pageNum).Order("created_at desc").Limit(pageSize).Find(&article).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	//fmt.Println(reflect.TypeOf(article[0].UpdatedAt.Format("2006-01-02 15:04:05")))
	return article, nil
}

//  统计用户发表文章操作数量  （阅读量， 推荐量， 点赞数量， 分享量， 收藏量）

// 添加文章
func AddArticle(data map[string]interface{}) error {
	article := Article{
		Title:             data["title"].(string),
		LabelId:           data["label_id"].(string),
		Content:           data["content"].(string),
		Cover:         data["cover_path"].(string),
		IsAd:              data["is_ad"].(bool),
		ArticleCategoryId: data["article_category_id"].(int),
		Sort:              data["sort"].(int),
		Author:            data["author"].(int),
		CreatedAt:         time.Now(),
		Status: 		   data["status"].(int),
	}
	if err := DB.Create(&article).Error; err != nil {
		return err
	}
	return nil
}

// 修改
func EditArticle(id int, data interface{}) error {
	if err := DB.Model(&Article{}).Where("id = ? and is_deleted = 0", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

// 根据条件统计文章总数

func GetArticleTotal(title string, timeWhere string,  maps interface{}) (int, error) {
	var count int
	if err := DB.Model(&Article{}).Where(maps).Where(title).Where(timeWhere).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

// 删除 (软删除)

func DeletedArticle(id int) error {
	logging.Info("id",id)
	if err := DB.Model(&Article{}).Where("id = ?", id).Update( "is_deleted", true).Error; err != nil {
		return err
	}
	return nil
}

// 文章撤回

func RevokeArticle(id int, data map[string]interface{})error{
	fmt.Println(data)
	if err := DB.Model(&Article{}).Where("id=? and is_deleted = 0", id).Updates(data).Error; err!=nil {
		return err
	}
	return  nil
}

// 统计操作数量
func SumOpera(userId int, opera string) (int, error) {
	//logging.Info("opera", opera)
	var sum int
	row := DB.Model(&Article{}).Where("author = ?", userId).Select("sum(" + opera + ")as total").Row()
	_ = row.Scan(&sum)
	return sum, nil
}



/**
	浏览量
 */
func GetReadingNum(mediaUserId int) int {
	var num int
	row := DB.Model(&Article{}).Select("sum(pageviews) as num").Where("author=?", mediaUserId).Row()
	row.Scan(&num)
	return num
}

func GetShareNum(mediaUserId int) int {
	var num int
	row := DB.Model(&Article{}).Select("sum(share_num)").Where("author=?", mediaUserId).Limit(3).Row()
	row.Scan(&num)
	return num
}

/**
	获取最新文章
 */
func GetNewArticle(author int) ([]*Article, error) {
	var result []*Article
	err := DB.Model(&Article{}).Where("author=?", author).Limit(3).Order("created_at desc").Find(&result).Error
	if err != nil {
		return nil, err
	}
	return result, nil
}


func GetArticleNum(mediaUserId int) int {
	var num int
	DB.Model(&Article{}).Where("author=?", mediaUserId).Where("status=2").Count(&num)
	return num
}